export default function init(canvas: any, ctx: CanvasRenderingContext2D) {

  interface iCircle {
    x: number,
    y: number,
    velocityX: number, //x速度
    velocityY: number, //y速度
    radius: number, //半径
    color: string
  }
  let circles: iCircle[] = [];

  /**
   * 创建一个渐变背景色
   */
  const createRect = () => {
    let gradient = ctx.createLinearGradient(30, 30, 160, 160)
    gradient.addColorStop(0, "yellow");
    gradient.addColorStop(0.5, "pink");
    gradient.addColorStop(1, "#abcdef");
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, document.body.clientWidth, document.body.clientHeight);
  }

  /**
    * 初始化canvas画布
  */
  const initCanvas = () => {
    ctx = canvas.value?.getContext('2d') as CanvasRenderingContext2D
    canvas.value!.width = document.body.clientWidth
    canvas.value!.height = document.body.clientHeight
    ctx.font = '32pt Ariel';
    ctx.canvas.onmousedown = function (e: Event) {
      e.preventDefault();
      e.stopPropagation();
    };
  }

  const initBall = () => {
    //创建100个球
    for (let i = 0; i < 20; ++i) {
      circles[i] = {
        x: 500,
        y: 300,
        velocityX: 3 * Math.random(), //x速度
        velocityY: 3 * Math.random(), //y速度
        radius: 50 * Math.random(), //半径
        color: 'rgba(' + (Math.random() * 255).toFixed(0) + ', ' +
          (Math.random() * 255).toFixed(0) + ', ' +
          (Math.random() * 255).toFixed(0) + ', 1.0)'
      };
    }
  }


  function adjustPosition(circle: any) {
    //边缘检测
    if (circle.x + circle.velocityX + circle.radius > ctx.canvas.width ||
      circle.x + circle.velocityX - circle.radius < 0)
      circle.velocityX = -circle.velocityX;

    //边缘检测
    if (circle.y + circle.velocityY + circle.radius > ctx.canvas.height ||
      circle.y + circle.velocityY - circle.radius < 0)
      circle.velocityY = -circle.velocityY;

    circle.x += circle.velocityX;
    circle.y += circle.velocityY;
  }

  function init() {
    initCanvas()
    initBall()
    createRect()
    let timer = setInterval(function draw() {
      ctx?.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      createRect()
      circles.forEach(function (circle) {
        ctx.beginPath();
        ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, false);
        ctx.fillStyle = circle.color;
        ctx.fill();
        adjustPosition(circle);
      })
    }, 1000 / 60);
    return timer
  }

  init()
}
